import LineMaterialProperty from '../lib/LineMaterialProperty'
import CircleWaveMaterialProperty from '../lib/CircleWave'
import { initLoad, callUIInteraction, addResponseEventListener } from '@/PixelStreaming/webrtcVideo.js'
export default {
    data() {
        return {
            image: require('@/assets/map/fxdline.png'),
            yyfxdVillIcon: require('@/assets/map/village/vill.png'),
            yyfxdVillBack: [
                require('@/assets/map/village/v_1.png'),
                require('@/assets/map/village/v_2.png'),
                require('@/assets/map/village/v_3.png'),
                require('@/assets/map/village/v_4.png')
            ],
            yyfxdVillImgs: [],
            yyfxdQyIcons: [
                require('@/assets/map/qsydw/qy.png'),
                require('@/assets/map/qsydw/qy.png'),
                require('@/assets/map/qsydw/qy.png'),
                require('@/assets/map/qsydw/qy.png')
            ],
            yyfxdTypeIcons: {
                jiZhen: [
                    require('@/assets/map/qsydw/jiZhen_1.png'),
                    require('@/assets/map/qsydw/jiZhen_2.png'),
                    require('@/assets/map/qsydw/jiZhen_3.png'),
                    require('@/assets/map/qsydw/jiZhen_4.png')
                ],
                cunLuo: [
                    require('@/assets/map/qsydw/cunLuo_1.png'),
                    require('@/assets/map/qsydw/cunLuo_2.png'),
                    require('@/assets/map/qsydw/cunLuo_3.png'),
                    require('@/assets/map/qsydw/cunLuo_4.png')
                ],
                jingQu: [
                    require('@/assets/map/qsydw/jingQu_1.png'),
                    require('@/assets/map/qsydw/jingQu_2.png'),
                    require('@/assets/map/qsydw/jingQu_3.png'),
                    require('@/assets/map/qsydw/jingQu_4.png')
                ],
                shiYeDanWe: [
                    require('@/assets/map/qsydw/shiYeDanWe_1.png'),
                    require('@/assets/map/qsydw/shiYeDanWe_2.png'),
                    require('@/assets/map/qsydw/shiYeDanWe_3.png'),
                    require('@/assets/map/qsydw/shiYeDanWe_4.png')
                ],
                qiYeDanWei: [
                    require('@/assets/map/qsydw/qiYeDanWei_1.png'),
                    require('@/assets/map/qsydw/qiYeDanWei_2.png'),
                    require('@/assets/map/qsydw/qiYeDanWei_3.png'),
                    require('@/assets/map/qsydw/qiYeDanWei_4.png')
                ],
                changKuang: [
                    require('@/assets/map/qsydw/changKuang_1.png'),
                    require('@/assets/map/qsydw/changKuang_2.png'),
                    require('@/assets/map/qsydw/changKuang_3.png'),
                    require('@/assets/map/qsydw/changKuang_4.png')
                ],
                other: [
                    require('@/assets/map/qsydw/other_1.png'),
                    require('@/assets/map/qsydw/other_2.png'),
                    require('@/assets/map/qsydw/other_3.png'),
                    require('@/assets/map/qsydw/other_4.png')
                ]
            },
            colorsYYFXD: ['#CE1F1F', '#F0810B', '#F0C90B', '#00A2FB'],
            eventFn: null,
        }
    },
    computed: {
        basin() {
            return this.$store.getters.basin
        },
        pageState() {
            return this.$store.getters.pageState
        }
    },
    watch: {
        $route: {
            handler: function (val, oldVal) {
                if (val.path !== '/Rehearsal' || val.path !== '/reserveplan/previewPlan') {
                    this.clearYYFXD()
                }
            },
            // 深度观察监听
            deep: true
        },
        pageState: {
            immediate: true,
            deep: true,
            handler: function (val, oldVal) {
                if (this.$route.path === '/Rehearsal') {
                    if (!val.yuYan_Load && val.yuYanInfoType === 'FXPG') {
                        console.log('进入风险评估' + val.planId);
                        var param = {
                            "basin": this.basin,
                            "eventName": "RehearsalFxpgEnter",  // 事件名称
                            "id": val.planId     // 预演编号
                        }
                        callUIInteraction("Web_RehearsalFxpgEnter", param);
                        var _this = this;
                        window.UE_RehearsalPoint = function (res) {
                            _this.RehearsalPoint(res)
                        }
                        this.getYYFXD(val.planId)
                    } else {
                        console.log('离开风险评估');
                        var param = {
                            "basin": this.basin,
                            "eventName": "RehearsalFxpgLeave",  // 事件名称
                            "id": val.planId     // 预演编号
                        }
                        callUIInteraction("Web_RehearsalFxpgLeave", param);
                        this.clearYYFXD()
                    }
                }
                if (this.$route.path === '/reserveplan/visualization') {
                    if (!val.yuAn_YYYA_Load && val.yuAn_YYYA_Right_Type === 1) {
                        console.log('预案--进入对照信息' + val.planId);
                        var param = {
                            "basin": this.basin,
                            "id": val.planId     // 预演编号
                        }
                        callUIInteraction("Web_ContrastinfoEnter", param);
                        var _this = this;
                        window.UE_RehearsalPoint = function (res) {
                            _this.RehearsalPoint(res)
                        }
                        this.getYYFXD(val.planId)
                    } else {
                        console.log('预案--离开对照信息' + val.planId);
                        var param = {
                            "basin": this.basin,
                            "id": val.planId     // 预演编号
                        }
                        callUIInteraction("Web_ContrastinfoLeave", param);
                        this.clearYYFXD()
                    }
                }
            }
        }
    },
    beforeDestroy() {
        var param = {
            "basin": this.basin,
            "eventName": "RehearsalFxpgLeave",  // 事件名称
        }
        callUIInteraction("Web_RehearsalFxpgLeave", param);
        this.clearYYFXD()
    },
    created() {
        this.yyfxdVillBack.forEach(item => {
            var img = new Image()
            img.src = item
            this.yyfxdVillImgs.push(img)
        })

        this.entitiesYYFXDI = []
        this.entitiesYYFXDMap = new Map()
        this.primitiveYYFXDI = []

        this.$eventBus.$on('flyToYYFXD', this.flyToYYFXD)
    },
    mounted() {
        this.lineMaterials = this.getLineMaterial()
    },
    methods: {
        //ue-web 风险分析地图图层点击
        RehearsalPoint(res) {
            var PointType = res.PointType;
            var prop = JSON.parse(res.params)
            console.log(prop)
            switch (PointType) {
                case '1':
                    var params = {
                        id: {
                            "eventName": prop.facilityType ? 'YYFXDType' : 'YYFXD',
                            "prop": prop
                        }
                    }
                    this.$eventBus.$emit('UE_RehearsalYYFXD', params)
                    break;
                case '2':
                    prop = prop.properties
                    var params = {
                        id: {
                            "eventName": '断面',
                            "prop": prop
                        }
                    }
                    this.$eventBus.$emit('UE_RehearsalDMX', params)
                    break;
                case '3':
                    prop.guid = prop.Guid || '';
                    var params = {
                        id: {
                            "eventName": '最大淹没范围',
                            "prop": prop
                        }
                    }
                    console.log(params);
                    this.$eventBus.$emit('UE_RehearsalYMFW', params)
                    break;

                default:
                    break;
            }
        },
        getLineMaterial() {
            var material = []
            // console.log(this.image)
            this.colorsYYFXD.forEach(item => {
                var mat = new Cesium.Material({
                    fabric: {
                        uniforms: // uniforms,
                        {
                            image: this.image,
                            animationSpeed: 0.001,
                            color: Cesium.Color.fromCssColorString(item),
                            repeat: new Cesium.Cartesian2(1.0, 1.0)
                        },
                        source: `czm_material czm_getMaterial(czm_materialInput materialInput)
                        {
                            czm_material material = czm_getDefaultMaterial(materialInput);
                            vec2 st = materialInput.st;
                            float time = czm_frameNumber * animationSpeed;
                            vec4 colorImage = texture2D(image, vec2(st.t,fract((st.s - time)) ));
                            vec4 fragColor;
                            fragColor.rgb = (colorImage.rgb+color.rgb) / 1.0;
                            fragColor = czm_gammaCorrect(fragColor);
                            material.alpha = colorImage.r;
                            material.diffuse = (colorImage.rgb+color.rgb)/2.0;
                            material.emission = fragColor.rgb;
                            return material;
                        }`
                    }
                })
                material.push(mat)
            })
            return material
        },
        getLinePrimitive(lineArr, lv) {
            var primitive = new Cesium.Primitive({
                geometryInstances: new Cesium.GeometryInstance({
                    geometry: new Cesium.PolylineGeometry({
                        positions: Cesium.Cartesian3.fromDegreesArrayHeights(lineArr),
                        width: 25
                    }),
                    attributes: {
                        color: Cesium.ColorGeometryInstanceAttribute.fromColor(this.colorsYYFXD[lv])
                    }
                }),
                appearance: new Cesium.PolylineMaterialAppearance({
                    translucent: true
                })

            })
            primitive.appearance.material = this.lineMaterials[lv]
            return primitive
        },
        drawYYFXDH(item, icons, z) {
            var h = 15
            var size = 15
            var lv = Number(item.level) - 1
            var lgtd = Number(item.lgtd)
            var lttd = Number(item.lttd)
            var entityBill = {
                eventName: 'YYFXD',
                prop: item,
                position: Cesium.Cartesian3.fromDegrees(lgtd, lttd, z + h),
                billboard: {
                    image: icons[lv],
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    heightReference: Cesium.HeightReference.NONE,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, this.$config.mapConfig.pb_far),
                    width: this.$config.mapConfig.billboardSize,
                    height: this.$config.mapConfig.billboardSize
                }
            }
            this.entitiesYYFXDMap.set(item.ewCode, this.$viewer.entities.add(entityBill))
        },
        drawYYFXD(item, icons) {
            var pos = [Cesium.Cartographic.fromDegrees(Number(item.lgtd), Number(item.lttd))]
            var z = 0
            if (this.$viewer.scene.terrainProvider.availability) {
                var promise = Cesium.sampleTerrainMostDetailed(this.$viewer.scene.terrainProvider, pos)
                promise.then(upos => {
                    z = upos[0].height
                    this.drawYYFXDH(item, icons, z)
                })
            } else {
                this.drawYYFXDH(item, icons, z)
            }
        },
        flyToYYFXD(id) {
            var entity = this.entitiesYYFXDMap.get(id)
            if (entity) {
                this.$viewer.flyTo(entity, {
                    duration: 0.5,
                    offset: {
                        heading: this.$viewer.camera.heading,
                        pitch: this.$viewer.camera.pitch,
                        range: 1000
                    }
                })
            }
        },
        getVillImg(img, txt) {
            return new Promise((resolve, reject) => {
                var size = 15
                var canvas = document.createElement('canvas')
                canvas.width = img.width * 1 // + 1有的字体较宽
                canvas.height = img.height * 1 // + 0.5有的字体较宽
                var ctx = canvas.getContext('2d')
                ctx.scale(2, 2) // 清晰一些

                ctx.drawImage(img, 0, 0, canvas.width / 2, canvas.height / 2)

                ctx.shadowOffsetX = -5 // 用来设定阴影在 X轴的延伸距
                ctx.shadowOffsetY = 5 // 用来设定阴影在 Y轴的延伸距
                ctx.shadowBlur = 0 // 设定阴影的模糊程度 默认0
                ctx.shadowColor = 'rgba(0, 0, 0, 0.85)' // 设定阴影颜色效果
                ctx.font = `bold ${size}px BlenderPro`
                ctx.textAlign = 'center'
                ctx.textBaseline = 'top'
                ctx.fillStyle = '#FFF'

                ctx.fillText(txt, canvas.width / 4, 10)

                const image = new Image()
                image.src = canvas.toDataURL('image/png')
                resolve(image)
            })
        },
        drawYYFXDVill(item) {
            var lv = Number(item.level) - 1
            var img = this.yyfxdVillImgs[lv]
            var name = item.ewName
            if (name.length > 4) {
                name = name.substring(0, 4) + '...';
            }
            var ewCode = item.ewCode
            // this.$eventBus.$emit('FZCHideXZC', ewCode)
            this.getVillImg(img, name).then(image => {
                var entityBill = {
                    eventName: 'YYFXD',
                    prop: item,
                    position: Cesium.Cartesian3.fromDegrees(
                        Number(item.lgtd),
                        Number(item.lttd),
                        20
                    ),
                    billboard: {
                        scale: 1,
                        image: image,
                        width: image.width / 2,
                        height: image.height / 2,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, this.$config.mapConfig.pb_far)
                    }
                }
                this.entitiesYYFXDMap.set(item.ewCode, this.$viewer.entities.add(entityBill))
            })
        },

        drawYYFXDType(item) {
            var lv = Number(item.level) - 1
            var lgtd = Number(item.lgtd)
            var lttd = Number(item.lttd)
            var facilityType = item.facilityType
            var imgs = this.yyfxdTypeIcons.qiYeDanWei
            switch (facilityType) {
                case '1':
                    imgs = this.yyfxdTypeIcons.jiZhen
                    break
                case '2':
                    imgs = this.yyfxdTypeIcons.cunLuo
                    break
                case '3':
                    imgs = this.yyfxdTypeIcons.jingQu
                    break
                case '4':
                    imgs = this.yyfxdTypeIcons.shiYeDanWe
                    break
                case '5':
                    imgs = this.yyfxdTypeIcons.qiYeDanWei
                    break
                case '6':
                    imgs = this.yyfxdTypeIcons.changKuang
                    break
                case '7':
                    imgs = this.yyfxdTypeIcons.other
                    break
            }
            var img = imgs[lv]
            var entityBill = {
                eventName: 'YYFXDType',
                prop: item,
                position: Cesium.Cartesian3.fromDegrees(lgtd, lttd, 20),
                billboard: {
                    image: img,
                    scale: 0.5,
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                    heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 2000),
                    width: 60,
                    height: 70
                }
            }
            this.entitiesYYFXDMap.set(item.ewCode, this.$viewer.entities.add(entityBill))
        },
        getYYFXD(id) {
            // 是否是风险评估

            this.clearYYFXD()

            this.$api.Get('/api/CalcPreview/GetRiskDrowning', {
                ID: id
            }, 'GetRiskDrowning').then(res => {
                res.data[0].infrastructurelst.forEach(item => {
                    this.drawYYFXDType(item)
                })
                res.data[0].villagelst.forEach(item => {
                    this.drawYYFXDVill(item)
                })
                this.initEventYYFXD(id)
            }).catch(() => { })
        },
        initEventYYFXD(id) {
            var eventFn = pickedObject => {
                if (
                    pickedObject &&
                    pickedObject.id &&
                    pickedObject.id.eventName
                ) {
                    console.log(pickedObject)
                    if (pickedObject.id.eventName === 'YYFXD') {
                        const dlgParams = this.$store.getters.dlgParams
                        dlgParams.name = 'DLGYYFXD'
                        console.log(pickedObject.id.prop)
                        pickedObject.id.prop['rvcd'] = pickedObject.id.prop.ewCode
                        pickedObject.id.prop['Ewcode'] = pickedObject.id.prop.ewCode
                        pickedObject.id.prop['id'] = id
                        // dlgParams.params = { ID: id, prop: pickedObject.id.prop }
                        dlgParams.params = pickedObject.id.prop// { ID: id, prop: pickedObject.id.prop }
                        this.$store.dispatch('dlgParams', dlgParams)
                    }
                    if (pickedObject.id.eventName === 'YYFXDType') {
                        const dlgParams = this.$store.getters.dlgParams
                        dlgParams.name = 'DLGYYFXD'
                        console.log(pickedObject.id.prop)
                        pickedObject.id.prop['rvcd'] = pickedObject.id.prop.townAdcd
                        pickedObject.id.prop['Ewcode'] = pickedObject.id.prop.townAdcd
                        pickedObject.id.prop['id'] = id
                        // dlgParams.params = { ID: id, prop: pickedObject.id.prop }
                        dlgParams.params = pickedObject.id.prop// { ID: id, prop: pickedObject.id.prop }
                        this.$store.dispatch('dlgParams', dlgParams)
                    }
                }
            }
            this.$eventBus.$on('UE_RehearsalYYFXD', res => {
                eventFn(res)
            })
            this.$store.getters.eventCesiumOption.leftPickFns.set('YYFXD', eventFn)

        },
        clearYYFXD() {
            if (window.cancelApi['GetRiskDrowning']) window.cancelApi['GetRiskDrowning']('cancel request')
            if (!this.entitiesYYFXDMap) return
            if (this.entitiesYYFXDMap.size > 0) {
                this.entitiesYYFXDMap.forEach((val, key) => {
                    this.$viewer.entities.remove(val)
                })
                this.entitiesYYFXDMap = new Map()
            }
            if (this.entitiesYYFXDI && this.entitiesYYFXDI.length > 0) {
                this.entitiesYYFXDI.forEach(item => {
                    this.$viewer.entities.remove(item)
                })
                this.entitiesYYFXDI = []
            }
            if (this.primitiveYYFXDI && this.primitiveYYFXDI.length > 0) {
                this.primitiveYYFXDI.forEach(item => {
                    this.$viewer.scene.primitives.remove(item)
                })
                this.primitiveYYFXDI = []
            }
        }
    }
}
